package org.usmile.algorithms.leetcode.middle;

import java.util.*;

/**
 * 130. 被围绕的区域
 *
 * 给你一个 m x n 的矩阵 board ，由若干字符 'X' 和 'O' ，找到所有被 'X' 围绕的区域，并将这些区域里所有的 'O' 用 'X' 填充。
 *
 * 示例 1：
 *
 * 输入：board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
 * 输出：[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
 * 解释：被围绕的区间不会存在于边界上，换句话说，任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上，或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻，则称它们是“相连”的。
 * 示例 2：
 *
 * 输入：board = [["X"]]
 * 输出：[["X"]]
 *
 * 提示：
 *
 * m == board.length
 * n == board[i].length
 * 1 <= m, n <= 200
 * board[i][j] 为 'X' 或 'O'
 */
public class _0130 {
}

class _0130_Solution {
    private static final int[][] DIRECTIONS = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

    public void solve(char[][] board) {
        int rows = board.length;
        int cols = board[0].length;
        boolean[][] visited = new boolean[rows][cols];
        Stack<int[]> stack = new Stack<>();
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (board[row][col] == 'O' && !visited[row][col]) {
                    visited[row][col] = true;
                    boolean needFill = true;
                    stack.push(new int[]{row, col});
                    List<int[]> points = new LinkedList<>();
                    while (!stack.isEmpty()) {
                        int[] curr = stack.pop();
                        points.add(curr);
                        int currRow = curr[0];
                        int currCol = curr[1];
                        if (currRow == 0 || currRow == rows - 1
                                || currCol == 0 || currCol == cols - 1) {
                            needFill = false;
                        }

                        for (int[] direction : DIRECTIONS) {
                            int nextRow = currRow + direction[0];
                            int nextCol = currCol + direction[1];
                            if (nextRow >= 0 && nextRow < rows && nextCol >= 0 && nextCol < cols) {
                                if (board[nextRow][nextCol] == 'O' && !visited[nextRow][nextCol]) {
                                    visited[nextRow][nextCol] = true;
                                    stack.push(new int[]{nextRow, nextCol});
                                }
                            }
                        }
                    }

                    if (needFill) {
                        for (int[] point : points) {
                            board[point[0]][point[1]] = 'X';
                        }
                    }
                }
            }
        }
    }
}